package com.zzs.esp.controller;

import com.zzs.esp.common.api.CommonResult;
import com.zzs.esp.common.utils.JwtTokenUtil;
import com.zzs.esp.dto.UserDTO;
import com.zzs.esp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author ZechariahZheng
 * @Date 2021/1/25 16:48
 * @Version 1.0
 * @description
 */
@Api(tags="TestController", description = "测试")
@RestController
public class TestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private UserService userService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @ApiOperation("登录以后返回token")
    @PostMapping("/admin/login")
    @ResponseBody
    public CommonResult login(@RequestBody UserDTO userDTO) {   //用户登录会得到一个token
        UserDetails userDetails = userService.loadUserByUsername(userDTO.getUsername());
        //校验密码是否正确
        if (!passwordEncoder.matches(userDTO.getPassword(), userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        //设置经过身份验证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        LOGGER.info("user name is: "+userDetails.getUsername());
        String token = jwtTokenUtil.generateToken(userDetails);
        LOGGER.info("token user is:"+jwtTokenUtil.getUserNameFromToken(token));
        //返回内容
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return CommonResult.success(tokenMap);
    }

    @ApiOperation("测试接口")
    @GetMapping("/admin/hello")
    @ResponseBody
    public CommonResult hello() {
        return CommonResult.success("hello world");
    }
}
